
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports _2bMatesSite.BO

Namespace _2bMatesSite
	''' <summary>
	''' Summary description for messages_group_bulletin.
	''' </summary>
	Public Partial Class messages_group_bulletin
		Inherits BaseWebPage
		Private strDefaultOrderBy As String = "Date"

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
			' Put user code to initialize the page here

			Response.Redirect(Constants.INBOX)
			If LoggedUser = Nothing Then
				Common.Utils.RedirectToLoginPage(Page)
			End If

			Dim usr As BO.User = LoggedUser

			Me.initPageTitles(Constants.MESSAGES_GROUP_BULLETIN_PAGE, "", Form1, Nothing, Nothing)
			Me.initAdvertisements(Form1, Nothing)

			If Constants.SHOW_GROUPS <> Constants.SHOW_ON Then
				Throw New Exception(Constants.ERROR_MESSAGE_NO_ACCESS)
			End If

			' Init with group bulletins which belongs to the groups the user is members of 
			' and for which the user has set "approve group bulletins" in his group accpunt settings
			Dim msgs As ArrayList = Messages.GetUserGroupBulletins(usr.ID, 0, -1)
			Dim MessagesCount As Double = msgs.Count
			If MessagesCount = 0 Then
				tblMessages.Visible = False
				lblNoMessages.Visible = True
			Else
				dgPager.RedirectPage = Constants.MESSAGES_GROUP_BULLETIN
				dgPager.MaxPageNumber = Convert.ToInt32(Math.Ceiling(MessagesCount / Constants.MAX_MESSAGES_ON_PAGE))
				dgPager.Action = "-1"
				dgPagerUp.RedirectPage = Constants.MESSAGES_GROUP_BULLETIN
				dgPagerUp.MaxPageNumber = Convert.ToInt32(Math.Ceiling(MessagesCount / Constants.MAX_MESSAGES_ON_PAGE))
				dgPagerUp.Action = "-1"

				' initialize listing literals
				dgPager.dgListing.TotalCount = Convert.ToInt32(MessagesCount)
				dgPagerUp.dgListing.TotalCount = Convert.ToInt32(MessagesCount)
				'initialize current page number
				If Convert.ToInt32(Request.Params("page")) = 0 OrElse dgPager.CurrentPageNumber = 1 Then
					dgPager.CurrentPageNumber = 1
					dgPagerUp.CurrentPageNumber = 1
					ViewState("StartIndex") = 0
				Else
					dgPager.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					dgPagerUp.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					ViewState("StartIndex") = (dgPager.CurrentPageNumber - 1) * Constants.MAX_MESSAGES_ON_PAGE
				End If

				dgPager.PagesRest = dgPager.MaxPageNumber - dgPager.FirstPageNumber + 1
				dgPager.LastPageNumber = Math.Min(dgPager.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)
				dgPagerUp.PagesRest = dgPagerUp.MaxPageNumber - dgPagerUp.FirstPageNumber + 1
				dgPagerUp.LastPageNumber = Math.Min(dgPagerUp.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)

				If Not IsPostBack Then
					dgMessages.VirtualItemCount = Convert.ToInt32(MessagesCount)
					BindGrid(strDefaultOrderBy)
				End If
			End If
		End Sub

		Protected Function CreateDataSource() As ICollection
			Dim usr As BO.User = LoggedUser

			Dim dt As New DataTable()
			Dim msgList As ArrayList
			Dim curMessageDate As DateTime

			' Init with group bulletins which belongs to the groups the user is members of 
			' and for which the user has set "approve group bulletins" in his group accpunt settings
			msgList = Messages.GetUserGroupBulletins(LoggedUser.ID, 0, -1)
			Dim LoggedUsersList As ArrayList = Common.Utils.GetLoggedUsersIDs()

			Dim MessagesCount As Integer = msgList.Count
			If MessagesCount <= 0 Then
				dgPager.FirstPageNumber = 1
				dgPager.LastPageNumber = 1
				dgPager.MaxPageNumber = 1
				dgPager.PagesRest = 1
				dgPager.dgListing.StartIndex = 0
				dgPager.dgListing.EndIndex = 0
				dgPagerUp.FirstPageNumber = 1
				dgPagerUp.LastPageNumber = 1
				dgPagerUp.MaxPageNumber = 1
				dgPagerUp.PagesRest = 1
				dgPagerUp.dgListing.StartIndex = 0
				dgPagerUp.dgListing.EndIndex = 0
				dgMessages.AllowSorting = False
			Else
				dgMessages.AllowSorting = True
				Dim startIndex As Integer = Convert.ToInt32(ViewState("StartIndex"))
				Dim endIndex As Integer = startIndex + Constants.MAX_MESSAGES_ON_PAGE
				Dim t As Integer = 0
				Dim counter As Integer = 0
				Dim pic As UserPicture
				endIndex = Math.Min(endIndex, MessagesCount)
				t = (endIndex - startIndex)
				dgPager.dgListing.StartIndex = startIndex + 1
				dgPager.dgListing.EndIndex = endIndex
				dgPagerUp.dgListing.StartIndex = startIndex + 1
				dgPagerUp.dgListing.EndIndex = endIndex

				Dim dr As DataRow
				dt.Columns.Add(New DataColumn("MessageID", GetType(Integer)))
				dt.Columns.Add(New DataColumn("Date", GetType(String)))
				dt.Columns.Add(New DataColumn("From", GetType(String)))
				dt.Columns.Add(New DataColumn("URL", GetType(String)))
				dt.Columns.Add(New DataColumn("FriendID", GetType(String)))
				dt.Columns.Add(New DataColumn("SenderName", GetType(String)))
				dt.Columns.Add(New DataColumn("OnlineImg", GetType(String)))
				dt.Columns.Add(New DataColumn("Subject", GetType(String)))
				dt.Columns.Add(New DataColumn("ViewMsgURL", GetType(String)))
				dt.Columns.Add(New DataColumn("MessageIDAndType", GetType(String)))
				dt.Columns.Add(New DataColumn("TypeImageURL", GetType(String)))
				dt.Columns.Add(New DataColumn("OnClickJS", GetType(String)))
				dt.Columns.Add(New DataColumn("TypeName", GetType(String)))

				' List user's inbox messages
				For Each msg As GroupBulletinMessage In msgList
					If counter >= startIndex AndAlso counter < endIndex Then

						dr = dt.NewRow()
						curMessageDate = msg.DateSent
						dr(0) = msg.ID
						dr(1) = Constants.ARR_MONTHS(curMessageDate.Month - 1) + " " + curMessageDate.Day + "<br />" + curMessageDate.ToShortTimeString()
						pic = msg.Sender.DefaultPicture
						If pic <> Nothing Then
							dr(2) = Pictures.GetPictureSrcFullURL(pic, True, "../")
							

						Else
							dr(2) = Constants.DEFAULT_THUMBNAIL_IMAGE_URL
						End If

						dr(3) = Users.ComposeMemeberLink(msg.Sender)
						dr(11) = Users.ComposeMemeberLinkOnClickJS(msg.Sender, trUserCanceledMessage)

						dr(4) = msg.SenderID.ToString()
						dr(5) = getBeginning(HttpUtility.HtmlEncode(msg.Sender.Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)

						If LoggedUsersList.Contains(msg.SenderID) Then
							dr(6) = "../images/online_status.gif"
						Else
							dr(6) = "../images/spacer.gif"
						End If

						If msg.GroupID > 0 Then
							dr(7) = "[" + msg.Group.Name + "] " + Server.HtmlEncode(msg.Subject)
						Else
							dr(7) = Server.HtmlEncode(msg.Subject)
						End If

						dr(8) = "../" + Constants.VIEW_MESSAGE + "?id=" + msg.ID + "&" + Constants.GROUP_PARAM + "=" + msg.GroupID + "&" + Constants.USER_MODE_PARAM + "=true"
						dr(9) = msg.ID + "-" + msg.MessageType

						If msg.MessageType = Messages.MessageType.mtBulletin Then
							dr(10) = Constants.BULLETIN_IMAGE_URL
							dr(12) = Constants.MSG_TYPE_NAME_BULLETIN
						Else
							dr(10) = Constants.MESSAGE_IMAGE_URL
							dr(12) = Constants.MSG_TYPE_NAME_GRP_BULLETIN
						End If

						dt.Rows.Add(dr)
					End If
					System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
				Next
			End If
			Dim dv As New DataView(dt)
			Return dv
		End Function

		Protected Sub BindGrid(ByVal orderBy As String)
			'init datagrid with database data ordered by "orederBy" param
			dgMessages.DataSource = CreateDataSource()
			dgMessages.DataBind()
			SetStyle()
		End Sub

		#region Web Form Designer generated code
		Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
			'
			' CODEGEN: This call is required by the ASP.NET Web Form Designer.
			'
			InitializeComponent()
			MyBase.OnInit(e)
		End Sub

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()
			AddHandler Me.dgMessages.ItemCommand, AddressOf Me.dgMessages_ItemCommand
			AddHandler Me.dgMessages.SortCommand, AddressOf Me.dgMessages_Sort
		End Sub
#End Region

		Private Sub dgMessages_Sort(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
			BindGrid(e.SortExpression)
		End Sub

		Private Sub dgMessages_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
			Dim cmd As String = e.CommandName

			If cmd.Equals("MemberRedirect") Then
				Response.Redirect(Constants.MEMBERS + "?id=" + e.CommandArgument)
			End If
		End Sub

		Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Dim cbCheckedValue As String
			Dim cb As CheckBox

			For Each dgi As DataGridItem In Me.dgMessages.Items
				cb = DirectCast(dgi.Cells(0).Controls(1), CheckBox)
				cbCheckedValue = Request.Params(dgi.Cells(0).Controls(1).UniqueID)

				If cbCheckedValue <> Nothing AndAlso cbCheckedValue.Equals("on") Then
					Dim idandtype As String() = cb.Attributes("value").Split("-"C)
					Dim MessageID As Integer = Convert.ToInt32(idandtype(0))
					Dim mailMsg As Message = Messages.GetUserGroupBulletin(LoggedUser.ID, -1, MessageID)
					mailMsg.IsMarkedDeleted = True
					mailMsg.Save()
				End If
			Next
			dgMessages.DataBind()
			Response.Redirect(Constants.MESSAGES_GROUP_BULLETIN)
		End Sub

		Private Sub SetStyle()
			Dim cb As CheckBox
			For Each dgi As DataGridItem In Me.dgMessages.Items
				cb = DirectCast(dgi.Cells(0).Controls(1), CheckBox)
				Dim idandtype As String() = cb.Attributes("value").Split("-"C)
				Dim MessageID As Integer = Convert.ToInt32(idandtype(0))
				Dim MessageType As String = idandtype(1)
				Dim msg As Message
				msg = Messages.GetUserGroupBulletin(LoggedUser.ID, -1, MessageID)
				If msg.IsRead Then
					dgi.CssClass = Constants.READ_MESSAGE_STYLE
				Else
					dgi.CssClass = Constants.UNREAD_MESSAGE_STYLE
				End If
			Next
		End Sub

	End Class
End Namespace






